﻿using CarAppDto.Sys.AdminDtos;
using CarAppDto.Sys.LoginDtos;
using CarAppService.Sys.IServices;
using D.UtilCore;
using D.UtilCore.Dtos;
using D.UtilCore.Filters;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace CarAppAPI
{
    /// <summary>
    /// 登录模块
    /// </summary>
    [Route("login")]
    public class LoginController : BaseApiController
    {
        private readonly IAdminService _adminService;

        /// <summary>
        /// 构造注入
        /// </summary>
        /// <param name="adminService"></param>
        public LoginController(IAdminService adminService)
        {
            _adminService = adminService;
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="inputLogin"></param>
        /// <returns></returns>
        [HttpPost("login"), TypeFilter(typeof(ExtActionFilterAttribute))]
        [AllowAnonymous]
        public async Task<ApiResult<string>> Login([FromBody] ReqLogin inputLogin)
        {
            return await _adminService.LoginAsync(inputLogin.Account, inputLogin.Password);
        }

        /// <summary>
        /// 请求刷新Token（以旧换新）
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        [HttpGet("refreshToken"), TypeFilter(typeof(ExtActionFilterAttribute))]
        [Authorize]
        public async Task<ApiResult<string>> RefreshToken(string token = "")
        {
            return await _adminService.RefreshTokenAsync(token);
        }

        /// <summary>
        /// 获取用户信息
        /// </summary> 
        /// <returns></returns>
        [HttpGet("getAdminInfo"), TypeFilter(typeof(ExtActionFilterAttribute))]
        [Authorize]
        public async Task<ApiResult<RepAdminInfo>> GetAdminInfo()
        {
            if (AdminId == null)
            {
                return new ApiResult<RepAdminInfo>()
                {
                    IsSuccess = false,
                    Code = StatusCodeEnum.Waring,
                    ErrorMsg = "登录过期，请重新登录"
                };
            }
            return await _adminService.GetAdminAsync(AdminId);
        }

        /// <summary>
        /// 登出操作
        /// </summary>
        /// <returns></returns>

        [HttpPost("logout"), TypeFilter(typeof(ExtActionFilterAttribute))]
        public ApiResult<int> Logout()
        {
            //await HttpContext.SignOutAsync(JwtBearerDefaults.AuthenticationScheme);
            return new ApiResult<int>();
        }
    }
}